<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <link rel="stylesheet" href="/static/style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="login-container">
    <h2>Login</h2>
    <form id="loginForm">
        <label for="phonenumber">手机号:</label>
        <input type="text" id="phonenumber" name="phonenumber" required>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
        <button type="submit">Login</button>
    </form>
    <div id="response-message"></div>
</div>
<!--模版语法-->
<!--<div>-->
<!--    <p>模版语法展示：</p>-->
<!--    {{ if .message }}-->
<!--    <div>-->
<!--        {{.message}}-->
<!--    </div>-->
<!--    {{end}}-->
<!--</div>-->

<script>
    $(document).ready(function() {
        $('#loginForm').submit(function(event) {
            event.preventDefault();

            const phonenumber = $('#phonenumber').val();
            const password = $('#password').val();

            $.ajax({
                url: '/login',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    "phonenumber":phonenumber,
                    "password":password }),
                success: function(response) {
                    console.log(response)//返回信息展示在控制台
                    // 保存token到localStorage，token根据handler中user的login函数内定义的uid和phonenumber生成
                    if (response.code == 0) {
                        localStorage.setItem('token', response.data.token);
                        $('#response-message').text('Login successful! Token saved.');
                        //跳转到首页
                        window.location.href = '/index'
                    }else{
                        alert("login failed:"+response.message)
                        $('#response-message').text('Login failed: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    $('#response-message').text('Login failed: ' + xhr.responseText);
                }
            });
        });
    });
</script>
</body>
</html>
